<?php
declare(strict_types=1);
// hook tick_worker_start.php

$http_server = $this->http_server;

$workerId = $serv->worker_id.'';
$istask = $serv->taskworker ? 'M' : 'W';
$workerIdk = $workerId . $istask;

$WorkersStatus = $this->_T('WorkersStatus');
$TWorkersStat= $this->_T('WorkersStat');

$WorkersStatus->set($workerId, ['Start' => time()]);
$last = $TWorkersStat->get($workerIdk);
if ($last != false) {
    $TWorkersStat->set($workerIdk, ['Request' => $last['Request'] + 1, 'LastRequest' => 0, 'Memory' => getum()]);
} else {
    $TWorkersStat->set($workerIdk, ['Request' => 0, 'LastRequest' => 0, 'Memory' => getum()]);
}

\Swoole\Timer::tick(10000, function ($id) use ($serv, $workerIdk,$TWorkersStat) {
    $d = $serv->stats();
    $last = $TWorkersStat->get($workerIdk);

    if ($last != false) {
        $TWorkersStat->set($workerIdk, ['Request' => $last['Request'] + ($d['worker_request_count'] - $last['LastRequest']), 'LastRequest' => $d['worker_request_count'], 'Memory' => getum()]);
    } else {
        $TWorkersStat->set($workerIdk, ['Request' => 0, 'LastRequest' => $d['worker_request_count'], 'Memory' => getum()]);
    }
});


// hook tick_worker_before.php

if ($workerId == 0) {

    // hook tick_worker_0_start.php


    //两小时换一次密钥

    $this->_T('Config')->set("authkey",['Value'=>get_uniqid(16)]);
    \Swoole\Timer::tick(86400000, function ($id) {
        $this->_T('Config')->set("authkey",['Value'=>get_uniqid(16)]);
    });

    \Swoole\Timer::tick(5000, function ($id) use ($serv) {
        $d = $serv->stats();
        $this->_T('Config')->set('start_time', ['Value' => $d['start_time']]);
        $this->_T('Config')->set('connection_num', ['Value' => $d['connection_num']]);
        $this->_T('Config')->set('request_count', ['Value' => $d['request_count']]);
    });

    \Swoole\Timer::tick(1000, function ($id) use ($serv) {
        $time = time();
        $s = date('s');
        $s == '02' && $this->http_server->task(['controller' => 'Task\Index', 'action' => 'frozen_at', 'data' => ['time' => $time]]);//每分钟 处理延迟到账
        $s == '05' && $this->http_server->task(['controller' => 'Task\Index', 'action' => 'views', 'data' => ['time' => $time]]);//各种浏览量统计//每分钟
    });

    // hook tick_worker_0_end.php
}


\Swoole\Timer::tick(1000, function ($id) use ($serv, $workerId,$WorkersStatus) {//每一秒通知服务状态
    $d = $serv->stats();
    $WorkersStatus->set($workerId, ['Request' => $d['worker_request_count'], 'Task' => $serv->taskworker ? 1 : 0, 'Pid' => $serv->worker_pid, 'Time' => time()]);
});


//5分钟 清理一次
/*
\Swoole\Timer::tick(300000, function ($id) {
    gc_mem_caches();
});
*/
?>